#!/bin/bash
# 启动 Lambda 模式（使用 LocalStack Lambda 处理事件）

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
DOCKER_DIR="$PROJECT_ROOT/docker"

echo "🚀 启动 Lambda 模式..."
echo "=================================================="

# 检查 .env 文件
if [ ! -f "$PROJECT_ROOT/.env" ]; then
    echo "⚠️  警告: .env 文件不存在"
    echo "💡 提示: 请复制 .env.example 为 .env 并配置 LLM_API_KEY"
    echo ""
fi

# 切换到项目根目录
cd "$PROJECT_ROOT"

# 停止所有处理器（包括 event-processor 和 Flink）
echo "🛑 停止现有处理器..."
docker-compose -f docker/docker-compose.yml stop \
  event-processor \
  flink-agents-processor \
  flink-cluster-processor \
  flink-cluster-processor-streaming \
  2>/dev/null || true

# 只启动基础服务（LocalStack + PostgreSQL）
echo "📦 启动基础服务（LocalStack + PostgreSQL）..."
docker-compose -f docker/docker-compose.yml up -d localstack postgres

# 等待服务启动
echo "⏳ 等待服务启动（10秒）..."
sleep 10

# 检查服务状态
echo ""
echo "📊 服务状态："
echo "=================================================="
docker ps --filter "name=browse-etl" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

# 检查 LocalStack 健康状态
echo ""
echo "🔍 检查 LocalStack 健康状态..."
for i in {1..30}; do
    if curl -s http://localhost:4566/_localstack/health > /dev/null 2>&1; then
        echo "✅ LocalStack 已就绪"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "⚠️  LocalStack 启动超时"
        exit 1
    fi
    echo "   等待中... ($i/30)"
    sleep 1
done

# 检查 PostgreSQL
echo ""
echo "🔍 检查 PostgreSQL..."
for i in {1..30}; do
    if docker exec browse-etl-postgres pg_isready -U postgres > /dev/null 2>&1; then
        echo "✅ PostgreSQL 已就绪"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "⚠️  PostgreSQL 启动超时"
        exit 1
    fi
    echo "   等待中... ($i/30)"
    sleep 1
done

# 部署 click-event-handler Lambda（API Gateway 入口）
echo ""
echo "📤 部署 click-event-handler Lambda..."
if [ -f "$SCRIPT_DIR/deploy-lambda-docker.sh" ]; then
    "$SCRIPT_DIR/deploy-lambda-docker.sh" || echo "⚠️  警告: click-event-handler 部署遇到错误，但继续执行..."
else
    echo "⚠️  警告: deploy-lambda-docker.sh 不存在，跳过"
fi

# 部署 behavior-processor Lambda（Kinesis 消费者）
echo ""
echo "📤 部署 behavior-processor Lambda..."
if [ -f "$SCRIPT_DIR/deploy-behavior-processor.sh" ]; then
    "$SCRIPT_DIR/deploy-behavior-processor.sh" || {
        echo "❌ 错误: behavior-processor 部署失败"
        exit 1
    }
else
    echo "❌ 错误: deploy-behavior-processor.sh 不存在"
    exit 1
fi

# 记录当前模式
echo "lambda" > /tmp/browse-etl-mode

echo ""
echo "=================================================="
echo "✅ Lambda 模式启动完成！"
echo "=================================================="
echo ""
echo "架构："
echo "  浏览器 → API Gateway → Lambda (click-event-handler)"
echo "                              ↓"
echo "                         Kinesis Stream"
echo "                              ↓"
echo "                  Lambda (behavior-processor) → PostgreSQL"
echo ""
echo "📝 快捷命令："
echo "   运行测试: make test"
echo "   查看日志: docker exec browse-etl-localstack awslocal logs tail /aws/lambda/behavior-processor"
echo "   查询数据: make query"
echo "   切换回 consumer.py: make start"
echo "=================================================="
